package com.jin.flashsaled.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jin.flashsaled.entity.*;
import com.jin.flashsaled.mapper.*;
import com.jin.flashsaled.service.IOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Date;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 靳鹏宇
 * @since 2025-09-18
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;
    @Autowired
    private SeckillOrderMapper seckillOrderMapper;
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    @Transactional()
    public Order buy(User user, Long goodsId) {
        Goods goods = goodsMapper.selectById(goodsId);
        SeckillGoods seckillGoods = seckillGoodsMapper.selectById(goodsId);
        //解决库存超卖
        //优化库存，在更新时，只有从数据库拿到的大于0，才能下单，在更新sql这里加限制条件，保证原子性
        LambdaUpdateWrapper<SeckillGoods> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(SeckillGoods::getGoodsId, goodsId).gt(SeckillGoods::getStockCount,0).set(SeckillGoods::getStockCount,seckillGoods.getStockCount()-1);
        int update = seckillGoodsMapper.update(queryWrapper);
        //如果库存扣失败，就返回null订单
        if (update<=0)
        {
            return null;
        }

        //商品库存减一
        String goodsStock=String.valueOf(Integer.parseInt(goods.getGoodsStock())-1);
        goods.setGoodsStock(goodsStock);
        //更新减完后的库存
        goodsMapper.updateById(goods);


        //创建订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goodsId);
        order.setOrderChannel("京东天猫");
        order.setStatus(0);
        order.setGoodsCount(1);
        order.setGoodsName(goods.getGoodsName());
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setDeliveryAddrId(0L);
        order.setCreateDate(LocalDateTime.now());
        //将订单插入数据库
        int orderIsFinish=orderMapper.insert(order);
        Order finishOrder=null;
        try {
            finishOrder=orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getUserId,user.getId()).eq(Order::getGoodsId,goodsId).eq(Order::getGoodsPrice,seckillGoods.getSeckillPrice()));
        }
        catch (TooManyResultsException e) {
            // 记录日志
            throw new RuntimeException("订单数据异常，查到多条", e); // ✅ Spring 会回滚
        }

        //创建秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setOrderId(finishOrder.getId());
        seckillOrder.setGoodsId(goodsId);
        seckillOrder.setUserId(user.getId());
        //将秒杀订单插入数据库
        int seckillOrderIsFinish= seckillOrderMapper.insert(seckillOrder);
        //加入redis缓存，加速查询是否重复抢购
        //使用userid+goodsid作为键将秒杀订单存放在seckillOrder目录下
        redisTemplate.opsForValue().set("seckillOrder:"+user.getId()+goodsId,seckillOrder);


        if (orderIsFinish==1 && seckillOrderIsFinish==1)
        {
            return order;
        }
        return null;
    }
}
